package com.pro.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.jdom2.JDOMException;
import org.oms.app.service.WXOrderQuery;
import org.oms.app.service.WXPay;
import org.oms.app.service.WXPrepay;
import org.oms.app.util.OrderUtil;
import org.oms.app.util.XMLUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.pro.course.service.CoreService;
import com.pro.course.util.SignUtil;
import com.pro.course.util.fina.WxSet;
import com.pro.pojo.AccessToken;
import com.pro.pojo.Jsticket;
import com.pro.pojo.Order;
import com.pro.pojo.User;
import com.pro.pojo.WxUserMsg;
import com.pro.service.UserService;
import com.pro.service.impl.OrderService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	@Resource
	private CoreService coreService;
	@Resource
	private OrderService orderService;

	/**
	 * 确认请求来自微信服务器
	 */
	/*
	 * @RequestMapping("/into") public Object into(HttpServletRequest
	 * request,HttpServletResponse response,Model model, HttpSession session)
	 * throws IOException{ // 微信加密签名 String signature =
	 * request.getParameter("signature"); // 时间戳 String timestamp =
	 * request.getParameter("timestamp"); // 随机数 String nonce =
	 * request.getParameter("nonce"); // 随机字符串 String echostr =
	 * request.getParameter("echostr");
	 * 
	 * PrintWriter out = response.getWriter(); //
	 * 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败 if
	 * (SignUtil.checkSignature(signature, timestamp, nonce)) {
	 * out.print(echostr); } out.close(); out = null; return "index"; }
	 */
	/**
	 * 跳转授权页面
	 */
	@RequestMapping(value = "/toRight.html", method = RequestMethod.GET)
	public void toRight(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.sendRedirect(coreService.getUserRight());
	}

	/**
	 * 获取授权
	 */
	@RequestMapping(value = "/getRight.html", method = RequestMethod.GET)
	public String getRight(Model model, HttpSession session, HttpServletRequest request) throws Exception {
		// 获取授权后code
		String code = request.getParameter("code");
		session.setAttribute("code", code);
		String state = request.getParameter("state");
		// 获取token
		AccessToken token = coreService.getAccessToken(code, state);
		System.out.println(token);
		// 获取用户微信信息
		WxUserMsg umsg = coreService.catchUserMsg(token);
		System.out.println(umsg);
		// 获得js票
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		session.setAttribute("ticket", ticket);
		System.out.println(ticket);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		// 设置时间
		umsg.setCreatTime(nowTime);
		System.out.println(umsg);
		// appid
		session.setAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "http://run.xuanzhen-tech.com/wx_project/user/getRight.html?code=" + code + "&state=STATE";
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		String openId = umsg.getOpenid();
		List<User> uList = userService.selectByOpenId(openId);
		Order od = orderService.selectOrderByOpenId(openId);
		
		session.setAttribute("userList", null);
		session.setAttribute("opid", openId);
		
		if (od!=null && "payment".equals(od.getOrderState())) {
			model.addAttribute("userList", uList);
			model.addAttribute("message", "无关信息");
			return "cg";
		} else if(od!=null && "non-payment".equals(od.getOrderState())){
			model.addAttribute("userList", uList);
			model.addAttribute("message", "无关信息");
			return "forward:pay";
		}else{
			// 存储用户微信信息
			userService.saveWxUser(umsg);
			session.setAttribute("userInfo", umsg);
			model.addAttribute("message", "无关信息");
			return "choose";
		}
	}

	private String skipToPayOrSuccess(Model model, HttpSession session) {
		String openId = (String) session.getAttribute("opid");
		Order od = null;
		List<User> uList = null;
		try {
			od = orderService.selectOrderByOpenId(openId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			uList = userService.selectByOpenId(openId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (od!=null && "payment".equals(od.getOrderState())) {
			model.addAttribute("userList", uList);
			model.addAttribute("message", "无关信息");
			return "cg";
		} else if(od!=null && "non-payment".equals(od.getOrderState())){
			model.addAttribute("userList", uList);
			model.addAttribute("message", "无关信息");
			return "forward:pay";
		}
		return null;
	}
	/**
	 * 表单提交跳转
	 */
	@RequestMapping(value = "/ad", method = RequestMethod.POST)
	public String toSignType(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code="";
		code = (String)session.getAttribute("code");
// 当前网页url
		String url="";
		 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		String sign=(String) session.getAttribute("signType");
		if (sign=="S") {
			return "forward:singleApply";
		}else if(sign=="G"){
			return "forward:addg";
		}else{
			return "forward:addg";
		}
	}
	/**
	 * 报名
	 */
	@RequestMapping(value = "/singleApply", method = RequestMethod.POST)
	public String singleApply(@ModelAttribute User user, Model model, HttpSession session, HttpServletRequest request)
			throws Exception {
		// 获取时间戳
				long timestamp = System.currentTimeMillis() / 1000;
				session.setAttribute("timestamp", timestamp);
				// 生成随机字符串
				String noncestr = RandomStringUtils.randomAlphanumeric(16);
				session.setAttribute("noncestr", noncestr);
				String code="";
				 code = (String)session.getAttribute("code");
		// 当前网页url
				String url="";
				 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
				if (request.getQueryString() != null) {
					url += "?" + request.getQueryString();
				}
				System.out.println(url);
				Jsticket ticket=(Jsticket) session.getAttribute("ticket");
				// 签名
				String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
				session.setAttribute("signature", signature);
				
				
		String forword = skipToPayOrSuccess(model, session);
		if (forword != null) {
			return forword;
		}
		System.out.println(user);
		// 设置创建时间
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		user.setCreatTime(nowTime);
		String opid = (String) session.getAttribute("opid");
		user.setOpenid(opid);
		int i = 1;
		i += userService.selectCount(user);
		String str = String.format("%04d", i);
		if (user.getSignType().equals("S")) {
			user.setRaceNo(user.getGender() + user.getRaceGroup() + str);
		}
		User us; 
		if(userService.selectUser(user)!=null){
			userService.updateUser(user);
		}else{
			us = userService.apply(user);
			model.addAttribute("raceNo", us.getRaceNo()); 
		}
	
		/*
		 * double s=(Math.random()*9000+1000); String race=""+s;
		 * user.setRaceNo(race);
		 */
		
	
		// 判定提交成功与否
		/*if (us != null) {
			model.addAttribute("message", "提交成功！");
			 model.addAttribute("raceNo", us.getRaceNo()); 
		} else {
			model.addAttribute("message", "发生错误！");
		}*/

		return "mzsm";
	}

	/**
	 * 报名
	 */
/*	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public String apply(@ModelAttribute User user, Model model, HttpSession session, HttpServletRequest request)
			throws Exception {
		System.out.println(user);

		// 设置创建时间
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		user.setCreatTime(nowTime);
		if (user.getSignType().equals("S")) {
			user.setRaceNo(user.getGender() + user.getRaceGroup() + "");
		} else {
			user.setRaceNo(user.getSignType() + user.getGender() + "");
		}
		
		 * double s=(Math.random()*9000+1000); String race=""+s;
		 * user.setRaceNo(race);
		 
		User us = userService.apply(user);
		// 判定提交成功与否
		if (us != null) {
			model.addAttribute("message", "提交成功！");
			 model.addAttribute("raceNo", us.getRaceNo()); 
		} else {
			model.addAttribute("message", "发生错误！");
		}
		return "redirect:cg";
	}*/

	@RequestMapping("/index")
	public String index(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		WxUserMsg user = new WxUserMsg();
		user.setOpenid("ofx1UweKlbaOe6LxTmjsVxXjDT9M");
		session.setAttribute("timestamp", "timestamp");
		session.setAttribute("signature", "signature");
		session.setAttribute("noncestr", "noncestr");
		session.setAttribute("appid", "appid");
		session.setAttribute("message", "无关信息");
		session.setAttribute("userInfo", user);
		session.setAttribute("opid", user.getOpenid());
		return "choose";
	}
	@RequestMapping("/ind")
	public String index1(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		WxUserMsg user = new WxUserMsg();
		user.setOpenid("ofx1UweKlbaOe6LxTmjsVxXjDT9M");
		session.setAttribute("timestamp", "timestamp");
		session.setAttribute("signature", "signature");
		session.setAttribute("noncestr", "noncestr");
		session.setAttribute("appid", "appid");
		session.setAttribute("message", "无关信息");
		session.setAttribute("userInfo", user);
		session.setAttribute("opid", user.getOpenid());
		return "index";
	}
	@RequestMapping(value = "/addf", method = RequestMethod.POST)
	public String addf(Model model, HttpServletRequest request, HttpSession session, User user) throws Exception {
		// 设置创建时间
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code="";
		 code = (String)session.getAttribute("code");
// 当前网页url
		String url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		/*
		 * Date now = new Date(); SimpleDateFormat dateFormat = new
		 * SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式 String nowTime
		 * = dateFormat.format( now ); user.setCreatTime(nowTime); int i=1;
		 * i+=userService.selectCount(user); String str =String.format("%04d",
		 * i); user.setSignType("f"); if(user.getSignType()=="f"){
		 * user.setRaceNo(user.getSignType()+user.getGender()+str); }
		 */
		List<User> userList = (List<User>) session.getAttribute("userList");
		if (userList == null) {
			userList = new ArrayList<User>();
		}
		Integer index = null;
		if (request.getParameter("sIndex") != null && !request.getParameter("sIndex").equals("")) {
			index = Integer.parseInt(request.getParameter("sIndex"));

		}
		if (index == null) {
			userList.add(user);
		} else {
			userList.set(index, user);
		}
		session.setAttribute("userList", userList);
		model.addAttribute("applyType", "fa");

		System.out.println(user);
		return "index2";
	}

	@RequestMapping(value = "/addg", method = RequestMethod.POST)
	public String addg(Model model, HttpServletRequest request, HttpSession session, User user) throws Exception {
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code="";
		 code = (String)session.getAttribute("code");
// 当前网页url
		String url="";
		 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
	String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		// 设置创建时间
		List<User> userListg = (List<User>) session.getAttribute("userListg");
		if (userListg == null) {
			userListg = new ArrayList<User>();
		}
		Integer index = null;
		if (request.getParameter("sIndex") != null && !request.getParameter("sIndex").equals("")) {
			index = Integer.parseInt(request.getParameter("sIndex"));

		}
		if (index == null) {
			userListg.add(user);
		} else {
			userListg.set(index, user);
		}
		session.setAttribute("userListg", userListg);
		model.addAttribute("applyType", "gr");

		
		return "redirect: toIndex3";
		
	}
	
	@RequestMapping(value = "/toIndex3", method = RequestMethod.GET )
	public String toIndex3(Model model) throws Exception {
		model.addAttribute("applyType", "gr");
		return "index3";
	}

	@RequestMapping(value = "/addgroup", method = RequestMethod.GET )
	public String addgroup(Model model, HttpServletRequest request, HttpSession session, User user) throws Exception {
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code = (String)session.getAttribute("code");
// 当前网页url
		String url="";
		 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		// 设置创建时间
		List<User> userListg = (List<User>) session.getAttribute("userListg");
		if (userListg == null) {
			userListg = new ArrayList<User>();
		}
		Integer index = null;
		if (request.getParameter("sIndex") != null && !request.getParameter("sIndex").equals("")) {
			index = Integer.parseInt(request.getParameter("sIndex"));

		}
		if (index == null) {
			userListg.add(user);
		} else {
			userListg.set(index, user);
		}
		session.setAttribute("userListg", userListg);
		model.addAttribute("applyType", "gr");

		
		return "index3";
	}
	@RequestMapping("/toUpdateUser")
	public String updateUser(Model model, HttpServletRequest request, HttpSession session, int index) throws Exception {
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code="";
		code = (String)session.getAttribute("code");
// 当前网页url
		String url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		
		
		
		List<User> userList = (List<User>) session.getAttribute("userList");

		model.addAttribute("updateUser", userList.get(index));
		model.addAttribute("applyType", "fa");
		return "bd";
	}

	@RequestMapping("/togrUpdateUser")
	public String togrUpdateUser(Model model, HttpServletRequest request, HttpSession session, int index)
			throws Exception {
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code="";
		code = (String)session.getAttribute("code");
// 当前网页url
		String url="";
		 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		
		
		List<User> userListg = (List<User>) session.getAttribute("userListg");

		model.addAttribute("updateUser", userListg.get(index));
		model.addAttribute("applyType", "gr");
		return "bd";
	}

	@RequestMapping("/fSubmit")
	public String fSubmit(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code = (String)session.getAttribute("code");
// 当前网页url
		String url = "http://run.xuanzhen-tech.com/wx_project/user/fSubmit?code=" + code + "&state=STATE";
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		
		String forword = skipToPayOrSuccess(model, session);
		if (forword != null) {
			return forword;
		}
		List<User> userList = (List<User>) session.getAttribute("userList");
		for (int j = 0; j < userList.size(); j++) {
			User user = userList.get(j);
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
			String nowTime = dateFormat.format(now);
			user.setCreatTime(nowTime);
			String opid = (String) session.getAttribute("opid");
			user.setOpenid(opid);
			int i = 1;
			i += userService.selectCount(user);
			String str = String.format("%04d", i);
			user.setSignType("F");
			/*
			 * WxUserMsg s= (WxUserMsg) session.getAttribute("userInfo");
			 * user.setOpenid(s.getOpenid());
			 */
		
			if (user.getSignType().equals("F")) {
				user.setRaceNo(user.getSignType() + user.getGender() + str);
			}
			userService.apply(user);
		}
		session.setAttribute("userList", null);
		return "mzsm";
	}

	@RequestMapping("/gSubmit")
	public String gSubmit(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code="";
		code = (String)session.getAttribute("code");
// 当前网页url
		String url="";
		 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		
		
		String forword = skipToPayOrSuccess(model, session);
		if (forword != null) {
			return forword;
		}
		List<User> userListg = (List<User>) session.getAttribute("userListg");
		for (int j = 0; j < userListg.size(); j++) {
			User user = userListg.get(j);
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
			String nowTime = dateFormat.format(now);
			user.setCreatTime(nowTime);
			String opid = (String) session.getAttribute("opid");
			user.setOpenid(opid);
			int i = 1;
			i += userService.selectCount(user);
			String str = String.format("%04d", i);
			user.setSignType("G");
			/*
			 * WxUserMsg s= (WxUserMsg) session.getAttribute("userInfo");
			 * user.setOpenid(s.getOpenid());
			 */
			
			if (user.getSignType().equals("G")) {
				user.setRaceNo(user.getSignType() + user.getGender() + str);
			}
			userService.apply(user);
		}
		session.setAttribute("userListg", null);
		return "mzsm";
	}

	@RequestMapping("/clean")
	public String clean(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code = (String)session.getAttribute("code");
// 当前网页url
		String url = "http://run.xuanzhen-tech.com/wx_project/user/clean?code=" + code + "&state=STATE";
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		
		String s = (String) session.getAttribute("opid");
		userService.deleteByOpenid(s);
		orderService.deleteByOpenId(s);
		session.setAttribute("userList", null);
		session.setAttribute("userListg", null);
		return "choose";
	}

	// 通知回调地址
	String notifyUrl = "http://run.xuanzhen-tech.com/wx_project/user/notice";

	@RequestMapping("/pay")
	public String pay(Model model, HttpServletRequest request, HttpSession session) throws Exception {

		/* WxUserMsg wxUser= (WxUserMsg) session.getAttribute("userInfo"); */
		String opid = (String) session.getAttribute("opid");
		/*
		 * List<User> userList=userService.selectByOpenId(wxUser.getOpenid());
		 */
		List<User> userList = userService.selectByOpenId(opid);
		User user = userList.get(0);
		int sum = userService.selectCountByOpenid(user);
		double money = 0;
		if (user.getSignType().equals("S")) {
			if(user.getRaceGroup().equals("A")||user.getRaceGroup().equals("B")){
				money = sum * 11800;
			}else{
			money = sum * 12800;
			}
		} else if (user.getSignType().equals("F")) {
			money = sum * 10800;
		} else if (user.getSignType().equals("G")) {
			money = sum * 9800;
		}
		Order order=orderService.selectOrderByOpenId(opid);
		if(order==null){
			order = new Order();
			order.setMoney(money);
			order.setOpenid(user.getOpenid());
			Date now = new Date();
			order.setCreatTime(now);
			String noncestr = RandomStringUtils.randomAlphanumeric(8);
			order.setOrderNo(noncestr);
			order.setOrderState("non-payment");
			orderService.saveOrder(order);
		}
		model.addAttribute("order", order);
		DecimalFormat df = new DecimalFormat("######0.00");
		String mo = df.format((double) (order.getMoney() / 100));
		model.addAttribute("money", mo);
		model.addAttribute("userList", userList);

		String spbill_create_ip = request.getRemoteAddr();
		WXPrepay prePay = new WXPrepay();
		prePay.setAppid(WxSet.APPID);
		prePay.setBody("抱走宝山报名-微信支付");
		prePay.setPartnerKey(WxSet.ParterKey);
		prePay.setMch_id(WxSet.ParterNo);
		prePay.setNotify_url(notifyUrl);
		prePay.setOut_trade_no(order.getOrderNo());
		prePay.setSpbill_create_ip(spbill_create_ip);
		System.out.println(money);
		prePay.setTotal_fee(((int)order.getMoney())+"");
		prePay.setTrade_type("JSAPI");
		prePay.setOpenid(user.getOpenid());
		// 此处添加获取openid的方法，获取预支付订单需要此参数！！！！！！！！！！！
		// 获取预支付订单号
		String prepayid = prePay.submitXmlGetPrepayId();
		System.out.println("获取的预支付订单是：" + prepayid);
		if (prepayid != null && prepayid.length() > 10) {
			// 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
			String jsParam = WXPay.createPackageValue(WxSet.APPID, WxSet.ParterKey, prepayid);
			System.out.println("jsParam=" + jsParam);
			// 此处可以添加订单的处理逻辑
			model.addAttribute("jsParam", jsParam);
			System.out.println("生成的微信调起JS参数为：" + jsParam);
		}

		return "pay";
	}

	@RequestMapping("/chanOrderState")
	public String changeOrderState(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		
	/*	// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code = (String)session.getAttribute("code");
// 当前网页url
		String url = "http://run.xuanzhen-tech.com/wx_project/user/chanOrderState?from=singlemes" + code + "&state=STATE";
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		*/
		
		
		String s = (String) session.getAttribute("opid");
		Order od = orderService.selectOrderByOpenId(s);
		od.setOrderState("payment");
		orderService.updateOrder(od);
		List<User> userList = userService.selectByOpenId(s);
		session.setAttribute("userList", userList);
		return "redirect: tocg";
	}
	@RequestMapping("/tocg")
	public String tocg(Model model, HttpServletRequest request, HttpSession session) throws Exception {
		
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code = (String)session.getAttribute("code");
// 当前网页url
		String url="";
		 url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket=(Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		
		String openId = (String) session.getAttribute("opid");
		List<User> uList = userService.selectByOpenId(openId);
		Order od = orderService.selectOrderByOpenId(openId);
		
		session.setAttribute("userList", null);
		session.setAttribute("opid", openId);
		
		if (od!=null && "payment".equals(od.getOrderState())) {
			model.addAttribute("userList", uList);
			model.addAttribute("message", "无关信息");
			return "cg";
		} else if(od!=null && "non-payment".equals(od.getOrderState())){
			model.addAttribute("userList", uList);
			model.addAttribute("message", "无关信息");
			return "forward:pay";
		}else{
			// 存储用户微信信息
			/*userService.saveWxUser(umsg);
			session.setAttribute("userInfo", umsg);*/
			model.addAttribute("message", "无关信息");
			return "forward:toRight.html";
		}
	}
	/**
	 * 通知调用方法
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/notice")
	public void notice(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		String result = new String(outSteam.toByteArray(), "utf-8");
		Map<String, String> map = null;
		try {
			map = XMLUtil.doXMLParse(result);
		} catch (JDOMException e) {
			e.printStackTrace();
		}

		// 此处调用订单查询接口验证是否交易成功
		boolean isSucc = reqOrderquery(map);
		// 支付成功，商户处理后同步返回给微信参数
		if (!isSucc) {
			// 支付失败
			System.out.println("支付失败");
		} else {
			System.out.println("===============付款成功==============");

			String orderNo = map.get("out_trade_no");
			Order order = orderService.selectOrderByNo(orderNo);
			order.setOrderState("payment");
			order.setTransactionId(map.get("transaction_id"));
			orderService.updateOrder(order);

			// ------------------------------
			// 处理业务开始
			// ------------------------------
			// 此处处理订单状态，结合自己的订单数据完成订单状态的更新
			// ------------------------------
			// 处理业务完毕
			// ------------------------------
			String noticeStr = setXML("SUCCESS", "");
			out.print(new ByteArrayInputStream(noticeStr.getBytes(Charset.forName("UTF-8"))));
		}
	}

	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

	/**
	 * 请求订单查询接口
	 * 
	 * @param map
	 * @param accessToken
	 * @return
	 */
	public static boolean reqOrderquery(Map<String, String> map) {
		WXOrderQuery orderQuery = new WXOrderQuery();
		orderQuery.setAppid(map.get("appid"));
		orderQuery.setMch_id(map.get("mch_id"));
		orderQuery.setTransaction_id(map.get("transaction_id"));
		orderQuery.setOut_trade_no(map.get("out_trade_no"));
		orderQuery.setNonce_str(map.get("nonce_str"));

		// 此处需要密钥PartnerKey，此处直接写死，自己的业务需要从持久化中获取此密钥，否则会报签名错误
		orderQuery.setPartnerKey(WxSet.ParterKey);

		Map<String, String> orderMap = orderQuery.reqOrderquery();
		// 此处添加支付成功后，支付金额和实际订单金额是否等价，防止钓鱼
		if (orderMap.get("return_code") != null && orderMap.get("return_code").equalsIgnoreCase("SUCCESS")) {
			if (orderMap.get("trade_state") != null && orderMap.get("trade_state").equalsIgnoreCase("SUCCESS")) {
				String total_fee = map.get("total_fee");
				String order_total_fee = map.get("total_fee");
				if (Integer.parseInt(order_total_fee) >= Integer.parseInt(total_fee)) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 解析微信发来的请求（XML）
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	/*
	 * @SuppressWarnings("unchecked") public static Map<String, String>
	 * parseXml(HttpServletRequest request) throws Exception { //
	 * 将解析结果存储在HashMap中 Map<String, String> map = new HashMap<String, String>();
	 * 
	 * // 从request中取得输入流 InputStream inputStream = request.getInputStream(); //
	 * 读取输入流 SAXReader reader = new SAXReader(); Document document =
	 * reader.read(inputStream); // 得到xml根元素 Element root =
	 * document.getRootElement(); // 得到根元素的所有子节点 List<Element> elementList =
	 * root.elements();
	 * 
	 * // 遍历所有子节点 for (Element e : elementList) map.put(e.getName(),
	 * e.getText());
	 * 
	 * // 释放资源 inputStream.close(); inputStream = null;
	 * 
	 * return map; } //处理微信推送
	 * 
	 * @RequestMapping("/daul") public void daul(HttpServletRequest request,
	 * HttpServletResponse response) throws ServletException, IOException { //
	 * 将请求、响应的编码均设置为UTF-8（防止中文乱码） request.setCharacterEncoding("UTF-8");
	 * response.setCharacterEncoding("UTF-8");
	 * 
	 * // 调用核心业务类接收消息、处理消息 String respMessage =
	 * CoreService.processRequest(request);
	 * 
	 * // 响应消息 PrintWriter out = response.getWriter(); out.print(respMessage);
	 * out.close(); }
	 */
}
